package com.example.qcrmdemo.Controller;

import com.example.qcrmdemo.entity.SalesPlan;
import com.example.qcrmdemo.service.SalesPlanService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SalesPlanController {
    private static final Logger logger = LoggerFactory.getLogger(SalesPlanController.class);
    //使用@Autowired注解标注成员变量，可以由Spring框架自动为这个变量赋值。
    //所同值是@Service标注的该连接口类型的实现类对象实例
    @Autowired
    private SalesPlanService salesPlanService;

    /**
     * 添加订单计划页面
     *
     * @return
     */
    @GetMapping("/YingXiaoGuanLi/salesPlan-new")
    public ModelAndView salesPlanAddView() {
        ModelAndView mav = new ModelAndView("YingXiaoGuanLi/salesPlan-new");
        return mav;
    }

    @GetMapping("/YingXiaoGuanLi/salesPlan")
    public ModelAndView salesPlanListView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ) {
        ModelAndView mav = new ModelAndView("YingXiaoGuanLi/salesPlan");
//        PageInfo<SalesPlan> page =salesPlanService.findByKeyword(pageNum,pageSize,keyword);
        PageInfo<SalesPlan> page=salesPlanService.selectAll();
        mav.addObject("page",page);
//        mav.addObject("keyword",keyword);
        return mav;
    }

    @GetMapping("/YingXiaoGuanLi/salesPlan-modify")
    public ModelAndView salesPlanModifyView(
            @RequestParam(name="id" ,required = true)int id,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name="keyword",required = false) String keyword

    ){
        ModelAndView mav=new ModelAndView("YingXiaoGuanLi/salesPlan-modify");
        //调用服务方法根据id查询要编辑的客户
        SalesPlan salesPlan=salesPlanService.findById(id);
        mav.addObject("salesPlan",salesPlan);
        return mav;
    }


    @PostMapping("/YingXiaoGuanLi/salesPlan-new")
    //@Validated注解所标注的参数，表明该参数中的属性需要按照属性上定义的验证规则进行验证。验证是由验证框架完成的。
    //验证的结果会以BindingResult实例的形式传入到该方法中
    public ModelAndView salesPlanAdd(@Validated SalesPlan salesPlan, BindingResult bindingResult){


        //redirect表示重定向响应
        //给浏览器仅发送一个请求地址，而没有任何视图内容或数据
        //浏览器会使用收到的地址，重新发动一个请求，由于是新的请求，因此没有缓存上一次请求的数据，从而达到防止对重复提交表单的目的
        ModelAndView mav=new ModelAndView("redirect:/YingXiaoGuanLi/salesPlan-new");
        Map<String,String> errorMessages=new HashMap<>();

        if(bindingResult.hasErrors()){
            //如果有验证错误信息，那么要进行处理
            //获得出现错误域，以及响应的错误消息文本
            final List<FieldError> fieldErrors=bindingResult.getFieldErrors();
            //错误信息放入到映射中
            for(FieldError error:fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加到映射集合中
                errorMessages.put(error.getField(),error.getDefaultMessage());
            }
            //将错误信息发送给视图
            mav.addObject("errorMessages",errorMessages);
            //将客户填写的信息，重新显示在表单中
            mav.addObject("salesPlan",salesPlan);
            //由于没有保存数据，因此不必进行重定向，内部转发请求到视图。同时，还要以保留请求数据，以及相应的信息。
            mav.setViewName("YingXiaoGuanLi/salesPlan-new");
        }else {
            //如果没有错误信息，验证通过，保存客户信息
            //调用服务方法保存客户数据
            boolean result=salesPlanService.append(salesPlan);
            if(result){
                logger.info("新增计划信息成功 - "+salesPlan);
            }else {
                logger.info("新增计划信息失败 - "+salesPlan);
            }
        }

        //调用服务方法保存客户数据
//        System.out.println(customerServise.append(customer));
        return mav;
    }


    @PostMapping("/YingXiaoGuanLi/salesPlan-modify")
    public ModelAndView salesPlanModify(
            SalesPlan salesPlan,
            @RequestParam(name="pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name="keyword",required = false) String keyword
    ) throws UnsupportedEncodingException {
//        String redirectUrl="redirect:/YingXiaoGuanLi/salesPlan?pageNum"+pageNum+"&pageSize="+pageSize+"&keyword="+ URLEncoder.encode(keyword,"utf-8");
        String redirectUrl="redirect:/YingXiaoGuanLi/salesPlan";
        ModelAndView mav=new ModelAndView(redirectUrl);
        boolean result=salesPlanService.modify(salesPlan);
        return mav;

    }

    @GetMapping("/YingXiaoGuanLi/salesPlan-remove")
    public ModelAndView salesPlanRemove(
            @RequestParam(name="id",required = true) int id,
            @RequestParam(name="pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name="pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name="keyword",required = false) String keyword

    ) throws UnsupportedEncodingException {
        String redirectUrl="redirect:/YingXiaoGuanLi/salesPlan?pageNum"+pageNum+"&pageSize="+pageSize+"&keyword="+ URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav=new ModelAndView(redirectUrl);
        boolean result=salesPlanService.remove(id);
        return mav;
    }



    @GetMapping("/YingXiaoGuanLi/salesPlan-details")
    public ModelAndView salesPlanXiangqingView() {
        ModelAndView mav = new ModelAndView("YingXiaoGuanLi/salesPlan-details");
        return mav;
    }


}
